package model

import "time"

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"fmt"
)

func init() {
	sql := beego.AppConfig.String("mysql")
	orm.RegisterDriver("mysql", orm.DRMySQL)
	orm.RegisterDataBase("default", "mysql", sql)
	orm.RegisterModel(new(Article))
	orm.RunSyncdb("default", false, true)
}

type Article struct {
	Id int       `orm:"column(id)" json:"article_id"`
	Title string `orm:"column(title)" json:"title"`
	Url string   `orm:"column(url);unique;" json:"url"`
	Type string  `orm:"column(type)" json:"type"`
	Status int `orm:"column(status)" json:"status"`
	CreateTime time.Time `orm:"column(create_time)" json:"create_time"`
	Chlname string `orm:"column(chlname);null" json:"chlname"`
	RewardFlag int `orm:"-" json:"reward_flag"`
	 // 1 原创
				// 0
}

func AddArticle(article Article) error{
	orm := orm.NewOrm()
	article.CreateTime = time.Now()
	_,err := orm.Insert(&article)
	return err
}


func UpdateArticle(article *Article) error{
	orm := orm.NewOrm()
	_,err := orm.Update(article,"status")
	return err
}


func ListArticle(typ string)  ([]Article,error){
	o := orm.NewOrm()
	articles :=  []Article{}

	s := ""
	if len(typ) == 0{
		s = "select * from article"
	}else{
		s = fmt.Sprintf(`select * from article where type = "%s"`,typ)
	}

	_,err := o.Raw(s).QueryRows(&articles)
	return articles,err
}

func ListArticleByPage(typ string,page int,size int)  (articles []Article,count int64,err error){
	o := orm.NewOrm()

	s := ""
	if len(typ) == 0{
		s = "select * from article order by id desc limit ?,?"
	}else{
		s = fmt.Sprintf(`select * from article where type = "%s" order by id desc limit ?,?`,typ)
	}

	_,err = o.Raw(s, (page-1)*size, size).QueryRows(&articles)
	if err != nil{
		return nil,0,err
	}

	sql := ``
	if len(typ) == 0{
		sql = "select count(*) from article"
	}else{
		sql = fmt.Sprintf(`select count(*) from article where type = "%s"`,typ)
	}

	err = o.Raw(sql).QueryRow(&count)
	if err != nil{
		return nil,0,err
	}
	return articles,count,err
}

func SearchArticleByPage(word string,page int,size int)  (articles []Article,count int64,err error){
	o := orm.NewOrm()

	s := fmt.Sprintf(`select * from article where title like '%s' order by id desc limit ?,?`,"%"+word+"%")

	_,err = o.Raw(s, (page-1)*size, size).QueryRows(&articles)
	if err != nil{
		return nil,0,err
	}

	sql := fmt.Sprintf(`select count(*) from article where title like '%s'`,"%"+word+"%")

	err = o.Raw(sql).QueryRow(&count)
	if err != nil{
		return nil,0,err
	}

	return articles,count,err
}





